package com.fish.gaiety.gateway.configuration;

import com.fish.gaiety.gateway.configuration.base.RequestContextBaseFilter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

@Component
@Slf4j
@RequiredArgsConstructor
public class RequestAuthorizationFilter extends OncePerRequestFilter {

    private final RequestContextBaseFilter requestContextBaseFilter;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (ObjectUtils.isEmpty(authentication))
            return;
        log.info("Request Filter. Current user: {}", authentication.getName());
        String requestId = UUID.randomUUID().toString();
        requestContextBaseFilter.filter();
        filterChain.doFilter(request, response);
        log.info("Filter end : {}", requestId);
    }
}
